﻿using BusinessLayer;
using Microsoft.SqlServer.Server;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data.Linq;
using System.Linq;
using System.Web;

namespace MvcOSGi.Shell.Infra
{
    public static class EnumerableExtensions
    {
        public static bool IsNullOrEmpty<T>(this ICollection<T> value)
        {
            return value == null || value.Count == 0;
        }

        public static bool IsNullOrEmpty<T>(this IEnumerable<T> value)
        {
            return value == null || !value.Any<T>();
        }

        public static bool IsNullOrEmpty(this IListSource value)
        {
            return value == null || value.GetList().Count == 0;
        }

        public static string Concatenate<T>(this IEnumerable<T> value)
        {
            return value.Concatenate(string.Empty);
        }

        public static string Concatenate<T>(this IEnumerable<T> value, string separator)
        {
            return string.Join(separator, value.Select(i => i.ToString()).ToArray());
        }

        //public static IEnumerable GetResult<TElement>(this Dictionary<BusinessLayer.Enums.DataBagKey, IMultipleResults> values, BusinessLayer.Enums.DataBagKey key)
        //{
        //    if (null != values && values.ContainsKey(key))
        //    {
        //        var result = values.Where(p => p.Key == key).FirstOrDefault();
        //        return result;
        //    }
        //    return new TElement[] { };
        //}

        public static IEnumerable<TElement> GetResult<TElement>(this Dictionary<BusinessLayer.Enums.DataBagKey, IMultipleResults> values, BusinessLayer.Enums.DataBagKey key)
        {
            if (null != values && values.ContainsKey(key))
            {
                var result = values.FirstOrDefault(i => i.Key == key).Value.GetResult<TElement>();
                if (!result.IsNullOrEmpty()) return result;
            }
            return new TElement[] { };
        }

        public static ReadOnlyCollection<TElement> GetReadOnlyCollection<TElement>(this Dictionary<BusinessLayer.Enums.DataBagKey, IMultipleResults> values, BusinessLayer.Enums.DataBagKey key)
        {
            if (null != values && values.ContainsKey(key))
            {
                var bag = values.FirstOrDefault(i => i.Key == key).Value as MultipleResultsBag;
                if (null != bag)
                {
                    var result = bag.GetReadOnlyCollection<TElement>();
                    if (!result.IsNullOrEmpty()) return result;
                }
            }
            return new ReadOnlyCollection<TElement>(new TElement[] { });
        }
    
    }
}